const cartmodel = require('../db/cart')
const {resinfo} = require('../utlis/utlis')

module.exports ={
    
    // 购物车添加 
    cartadd:async(req,res)=>{
        let{goodsid,userid,goodsnumber}=req.body
        if(!goodsid||!userid||!goodsnumber){
            resinfo(res,1,'参数缺失')
        }else{
            let data = await cartmodel.find({
                goodsid,
                userid
            })
            if(data.length){
               let updataResult =  await cartmodel.updateOne({
                    goodsid,
                    userid
                },{$set:{
                    goodsnumber: +data[0].goodsnumber + +goodsnumber
                }})
                if(updataResult){
                    resinfo(res,0,'购物车添加成功')
                }else{
                    resinfo(res,1,'购物车添加失败')
                }
            }else{
            let insertResult = await cartmodel.insertMany({
                goodsid,
                userid,
                goodsnumber
            })
            if(insertResult.length){
                    resinfo(res,0,'购物车添加成功')
                }else{
                    resinfo(res,1,'购物车添加失败')
                }
            }  
            }
    },

    // 获取购物车所有商品
    cartList:async(req,res)=>{
        let {id} = req.params
        let cartdata
        try{
            cartdata = await cartmodel.find({
                userid:id
            })
        }catch(err){
            resinfo(res,402,'购物车数据获取失败')
            return
        }

        if(cartdata.length){
            resinfo(res,0,'购物车数据获取成功',cartdata)
        }else{
            resinfo(res,1,'购物车数据获取失败')
        }
    },

    // 改变购物车的商品数量
    changnumber:async(req,res)=>{
        let {num,userid,goodsid} = req.body
        try{
            await cartmodel.updateOne({userid,goodsid},{$set:{goodsnumber:+num}})
        resinfo(res,0,'修改成功')
        }catch(err){
            resinfo(res,1,'修改失败')
        }
    },

    // 删除单个商品
    removeOne:async(req,res)=>{
        let {userid,goodsid} = req.body
        try{ 
        await cartmodel.deleteOne({
            userid,
            goodsid
        })
        resinfo(res,0,'删除成功')
        }catch(err){
         resinfo(res,1,'删除失败')
        }
    },

    // 删除所有选中的商品
    removechecked:async(req,res)=>{
        let {userid,goodsid} = req.body
        try{ 
        await cartmodel.deleteOne({
            userid,
            goodsid
        })
        resinfo(res,0,'修改成功')
        }catch(err){
            resinfo(res,1,'修改失败')
        }
    }
}